//
//  HNRepairController.m
//  shezhan
//
//  Created by 朱传正 on 2016/10/17.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNRepairController.h"
#import "HNMainController.h"
#import "ChatViewController.h"
#import "ApplyViewController.h"

@interface HNRepairController ()<UIWebViewDelegate>

@end

@implementation HNRepairController

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
      [self.navigationController.navigationBar setHidden:YES];
    
    NSString * _loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@%@?hnLoginName=%@",url_Base,url_WeiXiuYangHu,_loginName];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
  _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0, mainScreenSize.width, mainScreenSize.height)];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"====webViewDidFinishLoad");
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"] = self;
}

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    return YES;
}

#pragma -mark HNPublishProductJSExport - 设置返回
-(void)HNPublishProductJSExportBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
    }
    NSLog(@"-------goBack---------");

}

-(NSString *)HNPublishProductJSExportReturnLoginName{
    return [[EMClient sharedClient] currentUsername];
}

//微信支付、支付宝支付
-(void)HNpayOrder:(NSString *)backGoodsStr{
    NSDictionary *backGoodsDic = [AppConfig dictionaryWithJsonString:backGoodsStr];
    NSLog(@"backGoodsDic = %@",backGoodsDic);
    
    if ([[backGoodsDic objectForKey:@"type"] isEqualToString:@"1"]) {
        NSString *orderName = [backGoodsDic objectForKey:@"subject"];
        NSString *orderpPice = [backGoodsDic objectForKey:@"total_fee"];
        NSString *orderNumber = [backGoodsDic objectForKey:@"out_trade_no"];
        [HNAllJSExport WeiXinPayOrderName:orderName andOrderpPice:orderpPice andOrderNumber:orderNumber];
    }else if([[NSString stringWithFormat:@"%@",[backGoodsDic objectForKey:@"type"]] isEqualToString:@"0"]){
        NSString *orderName = [backGoodsDic objectForKey:@"subject"];
        NSString *orderpPice = [backGoodsDic objectForKey:@"total_fee"];
        NSString *orderNumber = [backGoodsDic objectForKey:@"out_trade_no"];
        NSString *orderDesc = [backGoodsDic objectForKey:@"body"];
        [HNAllJSExport AliPayOrderName:orderName andOrderpPice:orderpPice andOrderNumber:orderNumber andOrderDesc:orderDesc];
    }
    
}

//微信
-(void)viewDidAppear:(BOOL)animated{
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NotificationPayResult:) name:@"Order_PayControllerNotification" object:nil];
    
    //移除通知
    NSLog(@"======viewDidAppear");
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Order_PayControllerNotification" object:nil];
}
//微信支付通知回调
-(void)NotificationPayResult:(NSNotification *)notifi{
    NSLog(@"===NotificationPayResult:%@",notifi);
    NSDictionary * userinfoNoti = notifi.object;
    int retCode = [[userinfoNoti objectForKey:@"result"] intValue];
    if (retCode==0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"支付结果：订单支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertView.tag = 1001;
        [alertView show];
    }else{
        NSString * promptInfo = @"订单支付失败";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"支付结果：%@",promptInfo] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
}

-(void)HNSettingJSExportOutLogin{
    NSLog(@"HNSettingJSExportOutLogin");
    __weak HNRepairController *weakSelf = self;
    [self showHudInView:self.view hint:NSLocalizedString(@"setting.logoutOngoing", @"loging out...")];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] logout:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHud];
            if (error != nil) {
                [weakSelf showHint:error.errorDescription];
                NSLog(@"error.errorDescription = %@",error.errorDescription);
            }
            else{
                [[ApplyViewController shareController] clear];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
            }
        });
    });
}


#pragma -mark HNMyJSExport - 在线客服
-(void)HNMyJSExportOnlineService{
    NSLog(@"在线客服");
    [self setTitle:[NSString stringWithFormat:@"%ld",on_lineServiceTelPhone]];
}

-(void)setTitle:(NSString *)merchantPhone{
    //刷新加载头像数据
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:merchantPhone,@"hnLoginName", nil];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_UserInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
        if ([code isEqualToString:@"0"]) {
            NSDictionary *userInfo = [data objectForKey:@"data"];
            ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:merchantPhone conversationType:EMConversationTypeChat];
            chatController.title = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnNickName"]];
            NSLog(@"chatController.title = %@",chatController.title);
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.navigationController pushViewController:chatController animated:YES];
            });
        }else{
            //            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
            //            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        //        [self showHint:@"获取用户信息失败"];
    }];
}


@end
